package com.tyrone.algorithm.linear;

import java.util.Iterator;

public class Queue<T> implements Iterable<T>{
    //记录首结点
    private Node head;
    //当前栈的元素个数
    private int N;
    //记录最后一个结点
    private Node last;

    public Queue(){
        head=new Node(null,null);
        N=0;
        last=null;
    }
    /**
     * 判断队列是否为空，是返回true，否返回false
     * @return
     */
    public boolean isEmpty(){
        return N==0;
    }

    /**
     * 获取队列中元素的个数
     * @return
     */
    public int size() {
        return N;
    }

    /**
     * 从队列中拿出一个元素
     * @return
     */
    public T dequeue(){
        if (isEmpty()){
            return null;
        }
        Node node = head.next;
        head.next=node.next;
        N--;
        if (isEmpty()){
            last=null;
        }
        return node.item;
    }

    /**
     * 往队列中插入一个元素
     * @param t
     */
    public void enqueue(T t) {
        if(last==null){
            last = new Node(t,null);
            head.next=last;
        }else {
            Node oldLast =last;
            last = new Node(t,null);
            oldLast.next=last;
        }
        N++;
    }

    @Override
    public Iterator<T> iterator() {
        return new QIterator();
    }

    private class QIterator implements Iterator<T>{

        private Node n = head;

        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public T next() {
            Node node = n.next;
            n=n.next;
            return node.item;
        }

    }

    private class Node{
       public T item;
       public Node next;
       public Node(T item,Node node){
           this.item=item;
           this.next= node;
       }
   }
}
